//
//  GetClassWork.swift
//  BellManage
//
//  Created by Bestsch on 16/3/31.
//  Copyright © 2016年 wsl. All rights reserved.
//

import Foundation


/**
 解析json
 
 - parameter str: 服务器返回的字符串
 
 - returns: 数组
 */
func JsonFormt(str: String!) -> NSMutableArray {
    
    
    let result = str.replacingOccurrences(of: "\"null\"", with: "\"\"").replacingOccurrences(of: "null", with: "\"\"").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ")
    
    var json = JSON(data: (result.data(using: String.Encoding.utf8))!)
    
    if str.hasPrefix("{\"post\":") {
        json = json["post"]
    }
    let dataArray = NSMutableArray()
    if json.count > 0 {
        for i in 0..<json.count {
            dataArray.add(json[i])
        }
    }
    return dataArray
    
}
/**
 获取数据
 
 - parameter url:     接口地址
 - parameter request: 传递的xml字符串
 
 - returns: 数据数组
 */
func getData(_ url: String, request: String) ->  NSMutableArray{
    
    var result = HttpUtils.httpPostUTF(url, with: request)
    result = result?.replacingOccurrences(of: "\"null\"", with: "\"\"").replacingOccurrences(of: "null", with: "\"\"").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ").replacingOccurrences(of: "+", with: "%20");
    
    let json = JSON(data: (result?.data(using: String.Encoding.utf8))!)
    
    let dataArray = NSMutableArray()
    if json.count > 0 {
        for i in 0..<json.count {
            let dic = json[i]
            dataArray.add(dic)
        }
    }
    
    return dataArray
}

/**
 获取数据
 
 - parameter url:     接口地址
 - parameter request: 传递的xml字符串
 
 - returns: 数据数组
 */
func getDataWithNoPost(_ url: String, request: String) ->  NSMutableArray{
    
    let dataArray = NSMutableArray()
    var result = HttpUtils.httpPostUTF(url, with: request)
    result = result?.replacingOccurrences(of: "\"null\"", with: "\"\"").replacingOccurrences(of: "null", with: "\"\"").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ");
    print(result!)
    let json = JSON(data: (result?.data(using: String.Encoding.utf8))!)["post"]

    if json != nil && json.count > 0 {
        for i in 0..<json.count {
            let dic = json[i]
            dataArray.add(dic)
        }
    }

    
    return dataArray
}

/**
 获取uilabel的高度
 
 - parameter text:  文本
 - parameter font:  字体，大小
 - parameter wigth: 宽度
 
 - returns: 高度
 */
func getLabelHeight(_ text: String, font: UIFont, wigth: CGFloat) -> CGFloat {
    
    if text.characters.count == 0 {
        return 0
    }else{
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let attributes = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
        let string: NSString = text as NSString
        
        let s = string.boundingRect(with: CGSize(width: wigth, height: 0), options: option, attributes: attributes as? [String : AnyObject], context: nil)
        return s.height
    }
    
}
func getCommentTableHeight(_ comment: NSMutableArray) -> CGFloat {
    if comment.count == 0 {
        return 0 ;
    }else {
        var height: CGFloat = 0.0
        for i in 0...comment.count - 1 {
            let str = comment.object(at: i) as! String
            height += getLabelHeight(str, font: UIFont.systemFont(ofSize: 14) , wigth:screenW - 40) + 5
        }
        return height
    }
}
/**
 图片控件的高度
 
 - parameter photo: 图片数组
 
 - returns: 0
 */
func getPhotoCollectionHeight(_ photo: NSArray) -> CGFloat {
    if photo.count == 0{
        return 0
    }else if photo.count == 1 {
        let image = photo.object(at: 0) as! String
        if image.characters.count == 0 || image == "alse" {
            return 0
        }else {
            return 150
        }
        
    }else {
        let count = (photo.count%3)>0 ? 1: 0
        let row = photo.count/3 + count
        return CGFloat(Float(row)) * photoSize + CGFloat(Float((row - 1) * photoInsets + 10))
    }
}

func getPicCollectionHeight(_ photo: NSArray) -> CGFloat {
    
    let count = (photo.count%3)>0 ? 1: 0
    let row = photo.count/3 + count
    return CGFloat(Float(row)) * photoSize + CGFloat(Float((row - 1) * photoInsets + 10))
    
}

func getAddPhotoCollectionHeight(_ photo: NSArray) -> CGFloat {
    let n = photo.count + 1
    let count = (n%4)>0 ? 1: 0
    let row = n/4 + count
    return CGFloat(Float(row)) * AddphotoSize + CGFloat(Float((row - 1) * photoInsets + 10))
    
}

/**
 和当前时间比较贱格
 
 - parameter time: 时间
 
 - returns: 间隔，几天前。。。。。
 */
func getTimeSinceNow (_ time: String) -> String {
    let format = DateFormatter()
    let formatString = "yyyy-MM-dd HH:mm:ss"
    format.dateFormat = formatString
    let array: NSArray = time.components(separatedBy: ".") as NSArray
    var time1 = array.object(at: 0)
    time1 = (time1 as! String).replacingOccurrences(of: "T", with: " ")
    let date = format.date(from: time1 as! String)
    
    let late = date?.timeIntervalSince1970
    let now = Date().timeIntervalSince1970
    
    var timeString = ""
    let cha = now - late!
    
    if cha/60 < 1 {
        timeString = "刚刚"
    }else if cha/60 >= 1 && cha/3600 < 1 {
        let str = String(cha/60)
        let index = str.characters.index(str.endIndex, offsetBy: -14)
        timeString = str.substring(to: index) + "分钟前"
    }else if cha/3600 >= 1 && cha/86400 < 1 {
        let str = String(cha/3600)
        let index = str.characters.index(str.endIndex, offsetBy: -14)
        timeString = str.substring(to: index) + "小时前"
    }else if cha/86400 >= 1 && cha/2592000 < 1 {
        let str = String(cha/86400)
        let index = str.characters.index(str.endIndex, offsetBy: -14)
        timeString = str.substring(to: index)
        if timeString == "1" {
            timeString = "昨天"
        }else {
            timeString = timeString + "天前"
        }
    }else if cha/2592000 >= 1 && cha/311040000 < 1 {
        let str = String(cha/2592000)
        let index = str.characters.index(str.endIndex, offsetBy: -14)
        timeString = str.substring(to: index) + "个月前"
    } else {
        timeString = time1 as! String
    }
    return timeString;
}


func getTimeIntervalSinceNow (_ time: String) -> String {
    
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let timeDate = formatter.date(from: time)
    
    let num = Date().timeIntervalSince(timeDate!)
    print("\(num)")
    
    if num < 60 {
        let timeInterval = Int(num)/60
        return "刚刚\(timeInterval)秒前"
    }else if num < 60*60 {
        let timeInterval = Int(num)/(60)
        return "\(timeInterval)分钟前"
    }else if num < 60*60*24 {
        let timeInterval = Int(num)/(60*60)
        return "\(timeInterval)小时前"
    }else if num < 60*60*24*30 {
        let timeInterval = Int(num)/(60*60*24)
        return "\(timeInterval)天前"
    }else {
        let timeStrArr = (time as NSString).components(separatedBy: " ")
        let timeStr = (timeStrArr as NSArray).firstObject
        return "\(timeStr)"
    }
    
}



func getYMD(_ time: String) -> String {
    
    let format = DateFormatter()
    let formatString = "yyyy-MM-dd HH:mm:ss"
    format.dateFormat = formatString
    let array: NSArray = time.components(separatedBy: ".") as NSArray
    var time1 = array.object(at: 0)
    time1 = (time1 as! String).replacingOccurrences(of: "T", with: " ")
    let date = format.date(from: time1 as! String)
    Calendar.Identifier.gregorian
    let calendar = Calendar.init(identifier: Calendar.Identifier.gregorian)
    var comps = DateComponents.init()
    comps = ((calendar as NSCalendar?)?.components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day,NSCalendar.Unit.weekday,NSCalendar.Unit.hour,NSCalendar.Unit.minute,NSCalendar.Unit.second], from: date!))!
    
    let day = String(describing: comps.day)
    let month = String(describing: comps.month)
    let year = String(describing: comps.year)
    
    return day + "\n" + year + "." + month
    
}

func getweek(_ time: String) -> String {
    
    let format = DateFormatter()
    let formatString = "yyyy-MM-dd HH:mm:ss"
    format.dateFormat = formatString
    let array: NSArray = time.components(separatedBy: ".") as NSArray
    var time1 = array.object(at: 0)
    time1 = (time1 as! String).replacingOccurrences(of: "T", with: " ")
    let date = format.date(from: time1 as! String)
    
    let calendar = Calendar.init(identifier: Calendar.Identifier.gregorian)
    var comps = DateComponents.init()
    comps = ((calendar as NSCalendar?)?.components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day,NSCalendar.Unit.weekday,NSCalendar.Unit.hour,NSCalendar.Unit.minute,NSCalendar.Unit.second], from: date!))!
    
    let day = String(describing: comps.day!)
    let month = String(describing: comps.month!)
//    let year = String(comps.year)
    let weekNumber = comps.weekday
    var weekDay = ""
    switch (weekNumber!) {
    case 1:
        weekDay="星期日";
        break;
    case 2:
        weekDay="星期一";
        break;
    case 3:
        weekDay="星期二";
        break;
    case 4:
        weekDay="星期三";
        break;
    case 5:
        weekDay="星期四";
        break;
    case 6:
        weekDay="星期五";
        break;
    case 7:
        weekDay="星期六";
        break;
        
    default:
        break;
    }
    
    return month + "月 " + day + "日 " + weekDay
    
}
